import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { UseGuards } from '@nestjs/common';
import { GqlAuthGuard } from '../../guards/auth.guard';
import {
  TimetableRecordResult,
  TimetableRecordResults,
} from './dto/result-timetableRecord.output';
import { TimetableRecordType } from './dto/timetableRecord.type';
import { TimetableRecordService } from './timetableRecord.service';
import { PageInput } from '../../dto/page.input';
import { FindOptionsWhere } from 'typeorm';
import { Result } from '../../dto/result.type';
import { CurUserId } from '../../decorators/current-user.decorator';
import { TimetableRecord } from './models/timetableRecord.entity';
import { CardRecordService } from '../cardRecord/cardRecord.service';
import { cardTypeType } from '../card/models/card.entity';

@Resolver(() => TimetableRecordType)
export class TimetableRecordResolver {
  constructor(
    private readonly timetableRecordService: TimetableRecordService,
    private readonly cardRecordService: CardRecordService,
  ) {}

  @UseGuards(GqlAuthGuard)
  @Query(() => TimetableRecordResult)
  async gettimetableRecordInfo(
    @Args('id') id: string,
  ): Promise<TimetableRecordResult> {
    const result = await this.timetableRecordService.findById(id);
    if (result) {
      return {
        data: result,
        message: '获取成功',
        code: true,
      };
    }
    return {
      code: false,
      message: '课程表记录不存在',
    };
  }

  @UseGuards(GqlAuthGuard)
  @Query(() => TimetableRecordResults)
  async gettimetableRecords(
    @Args('page') page: PageInput,
    @Args('timetableId', { nullable: true }) timetableId: string,
    @CurUserId() studentId: string,
  ): Promise<TimetableRecordResults> {
    const { pageNum, pageSize } = page;
    const where: FindOptionsWhere<TimetableRecord> = {
      studentId,
    };
    if (timetableId) {
      where.timetableId = timetableId;
    }
    const [results, total] =
      await this.timetableRecordService.findTimetableRecords({
        start: pageNum === 1 ? 0 : (pageNum - 1) * pageSize,
        length: pageSize,
        where,
      });
    if (results) {
      return {
        data: results,
        page: {
          pageNum,
          pageSize,
          total,
        },
        message: '获取成功',
        code: true,
      };
    } else {
      return {
        code: false,
        message: '获取失败',
      };
    }
  }

  @UseGuards(GqlAuthGuard)
  // 取消预约课程
  @Mutation(() => Result)
  async deleteTimetableRecord(
    @Args('id') id: string,
    @CurUserId() userId: string,
  ): Promise<Result> {
    // 校验
    const result = await this.timetableRecordService.findById(id);
    if (!result) {
      return {
        message: '课程表记录不存在',
        code: false,
      };
    }
    // 删除课程记录
    const delRes = await this.timetableRecordService.deleteById(id, userId);
    if (!delRes) {
      return {
        message: '删除课程记录失败',
        code: false,
      };
    }
    // 回退消费卡记录
    const cardRecord = await this.cardRecordService.findById(
      result.cardRecordId,
    );
    if (!cardRecord) {
      return {
        message: '消费卡记录不存在',
        code: false,
      };
    }
    if (JSON.parse(cardRecord.card).type === cardTypeType.TIME) {
      const res = await this.cardRecordService.updateById(result.cardRecordId, {
        residueTime: cardRecord.residueTime + 1,
      });
      if (!res) {
        return {
          message: '消费卡记录回退失败',
          code: false,
        };
      }
    }

    return {
      message: '取消预约成功',
      code: true,
    };
  }

  @UseGuards(GqlAuthGuard)
  @Query(() => TimetableRecordResults)
  async getTimetableRecordsPc(
    @Args('page') page: PageInput,
    @Args('timetableId') timetableId: string,
  ): Promise<TimetableRecordResults> {
    const { pageNum, pageSize } = page;
    const where: FindOptionsWhere<TimetableRecord> = { timetableId };
    const [results, total] =
      await this.timetableRecordService.findTimetableRecords({
        start: pageNum === 1 ? 0 : (pageNum - 1) * pageSize,
        length: pageSize,
        where,
      });
    if (results) {
      return {
        data: results,
        page: {
          pageNum,
          pageSize,
          total,
        },
        message: '获取成功',
        code: true,
      };
    } else {
      return {
        code: false,
        message: '获取失败',
      };
    }
  }
}
